<template>
  <div ref="ele" class="global-graph">
  </div>
</template>

<script>
/*eslint-disable*/
import echarts from "echarts";
import axios from "axios";
import Debug from "debug";
import format_number from "format-number";
import ntdmn from "number-to-date-month-name";
import day_of_week from "day-of-week";

let formatter = format_number();
// import "static/macarons.js";
const dbg = Debug("[global.vue]");
dbg.enabled = true;

export default {
  data() {
    return {
      dates: [],
      raw_datas: [],
      chart: null,
      selected: {
        dates: [],
        types: []
      }
    };
  },
  computed: {
    type_counts() {
      return this.$store.state["abnormal_type2count"];
    },
    starterId() {
      return this.$store.state.starterId;
    },
    abnormal_type2color() {
      return this.$store.state.abnormal_type2color;
    },
    abnormal_type2comment() {
      return this.$store.getters["abnormal_type2comment"];
    },
    selectedDatas() {
      let params = this.selected["dates"].concat(this.selected["types"]);
      return params.join("&");
    },
    gray_colors() {
      return this.$store.state["gray_colors"];
    },
    font_size() {
      return this.$store.getters["axis_font_size"];
    },
    /**@description 把第二个Legend块往下移动 */
    debug_plus() {
      return 6;
    },
    opt_graphic() {
      return [
        {
          type: "group",
          left: 13,
          top: 8,
          children: [
            {
              type: "text",
              style: {
                text: "Glyphs",//"Legend Icon",
                font: `${this.fontSize}px`,
                fill: this.gray_colors[1]
              }
            },
            {
              type: "line",
              top: 13,
              shape: {
                x1: 0,
                x2: 105,
                y1: 0,
                y2: 0
              },
              style: {
                stroke: this.gray_colors[1]
              }
            }
          ]
        },
        {
          type: "group",
          left: 13,
          top: 95 + this.debug_plus,
          children: [
            {
              type: "text",
              style: {
                text: "Typical Start Modes",
                font: `${this.fontSize}px`,
                fill: this.gray_colors[1]
              }
            },
            {
              type: "line",
              top: 13,
              shape: {
                x1: 0,
                x2: 105,
                y1: 0,
                y2: 0
              },
              style: {
                stroke: this.gray_colors[1]
              }
            }
          ]
        },
        {
          type: "group",
          left: 13,
          top: 165,
          children: [
            {
              type: "text",
              style: {
                text: "Atypical Start Modes",
                font: `${this.fontSize}px`,
                fill: this.gray_colors[1]
              }
            },
            {
              type: "line",
              top: 13,
              shape: {
                x1: 0,
                x2: 105,
                y1: 0,
                y2: 0
              },
              style: {
                stroke: this.gray_colors[1]
              }
            }
          ]
        }
      ];
    },
    bar_item_style_getter() {
      return abnormal_type => {
        let opt = {
          emphasis: {
            barBorderWidth: 1,
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowOffsetY: 0,
            shadowColor: "rgba(0,0,0,0.5)"
          }
        };
        // debugger
        opt["color"] = this.abnormal_type2color[
          this.abnormal_type2comment[abnormal_type]
        ];
        // debugger;
        return opt;
      };
    },
    bar_tooltip_options() {
      let vue = this;
      return {
        formatter: function(params, ticket, callback) {
          let date = params["data"][0];
          let count = params["data"][1];
          let type_id = params["seriesName"].replace("type:", "");
          let result = `Date : ${date}<br>Mode : ${
            ($=>{
              let str = vue.abnormal_type2comment[type_id];
              if(str.startsWith("C")){
                str = str.replace("C","T");
              }
              return str;
            })()
          }<br>Count : ${count}`;
          return result;
        },
        textStyle: {
          color: "#FFFFFF"
        },
        extraCssText: "text-align: left;"
      };
    },
    abnormal_series() {
      let obj = {
        name: `type:-1`,
        type: "bar",
        // stack: "abnormal",
        itemStyle: this.bar_item_style_getter("-1"),
        barCategoryGap: "20%", //默认值
        data: this.raw_datas.map(e => [
          e.date,
          // e.counts["-1"] / e.total,
          e.counts["-1"]
        ]),
        xAxisIndex: 1,
        yAxisIndex: 1,
        stack: "abnormal",
        tooltip: this.bar_tooltip_options
        // markPoint: {
        //   name: "最大",
        //   type: "max"
        // }
        // $count_total:this.type_counts['-1']
      };
      return obj;
    },
    normal_series() {
      let serieses = [];
      for (let type in this.type_counts) {
        if (type != "-1") {
          let s = {
            name: `type:${type}`,
            type: "bar",
            // stack: "normal",
            itemStyle: this.bar_item_style_getter(type),
            // xAxisIndex: 0,
            // yAxisIndex: 0,
            z: 4,
            data: this.raw_datas.map(e => [e.date, e.counts[type]]),
            tooltip: this.bar_tooltip_options
            // barMinHeight:2
          };
          // debugger;
          if (this.abnormal_type2comment[type].startsWith("C")) {
            //C1 C2
            s["stack"] = "normal";
            s["xAxisIndex"] = 0;
            s["yAxisIndex"] = 0;
          } else {
            //A1 A2 ...
            s["stack"] = "abnormal";
            s["xAxisIndex"] = 1;
            s["yAxisIndex"] = 1;
          }
          serieses.push(s);
        }
      }
      // debugger
      return serieses;
    },
    bar_serieses() {
      let s = [...this.normal_series];
      s = _.sortBy(s, e => {
        let type_id = e.name.replace("type:", "");
        let count = this.type_counts[type_id];
        return -count;
      });
      return [...s, this.abnormal_series];
    },
    center_rect_series_has_tests() {
      let vue = this;
      return {
        name: "rect-1",
        type: "custom",
        data: this.raw_datas.map(e => {
          return [e.date, e.total];
        }),
        xAxisIndex: 2,
        yAxisIndex: 2,
        renderItem: function renderRect(params, api) {
          let value0 = api.value(0);
          // let dayInWeek = day_of_week.get(
          //   new Date(vue.dates[params.dataIndex]),
          //   "Asia/Shanghai"
          // );
          // let isBusinessDay = dayInWeek % 6 > 0;
          // console.log
          let value1 = api.value(1);
          let sized = api.size([value0, value1]);
          let coorded = api.coord([value0, value1]);
          return {
            type: "group",
            children: [
              {
                type: "rect",
                shape: {
                  height: params.coordSys.height,
                  x: coorded[0] - sized[0] / 2 + sized[0] * 0.1,
                  y: params.coordSys.y,
                  width: sized[0] * 0.8
                },
                style: {
                  fill: value1 == 0 ? "transparent" : "#dcdcdc00",
                  stroke: vue.gray_colors[2],
                  lineWidth: 1,
                  shadowBlur: 0
                }
              },
              {
                type: "line",
                shape: {
                  x1: coorded[0] - sized[0] / 2 + sized[0] * 0.1,
                  y1: params.coordSys.y,
                  x2: coorded[0] - sized[0] / 2 + sized[0] * 0.9,
                  y2: params.coordSys.y + params.coordSys.height
                },
                style: {
                  stroke: value1 == 0 ? "transparent" : vue.gray_colors[2]
                }
              },
              {
                type: "line",
                shape: {
                  x1: coorded[0] - sized[0] / 2 + sized[0] * 0.9,
                  y1: params.coordSys.y,
                  x2: coorded[0] - sized[0] / 2 + sized[0] * 0.1,
                  y2: params.coordSys.y + params.coordSys.height
                },
                style: {
                  stroke: value1 == 0 ? "transparent" : vue.gray_colors[2]
                }
              }
            ]
          };
        },
        tooltip: {
          formatter: function(params) {
            let date = params["data"][0];
            let total = params["data"][1];
            return `date : ${date}<br>total : ${total}`;
          },
          extraCssText: "text-align: left;"
        }
      };
    },
    center_rect_series_is_business_day() {
      let vue = this;
      return {
        name: "rect-2",
        type: "custom",
        data: this.raw_datas.map(e => {
          /**@type {Number[]} y_m_d */
          let y_m_d = e.date.split("-").map(e => parseInt(e));
          if (y_m_d[0] == 2016) {
            if (y_m_d[1] == 4) {
              if (y_m_d[2] >= 2 && y_m_d[2] <= 4) {
                return [e.date, false, "bank holiday"]; //清明节
              }
              if (y_m_d[2] == 30) {
                return [e.date, false, "bank holiday"]; //劳动节
              }
            }
            if (y_m_d[1] == 5) {
              if (y_m_d[2] == 1 || y_m_d[2] == 2) {
                return [e.date, false, "bank holiday"]; //劳动节
              }
            }
          }
          if (y_m_d[0] == 2015) {
            if (y_m_d[1] == 9) {
              if (y_m_d[2] == 26 || y_m_d[2] == 27) {
                return [e.date, false, "bank holiday"]; //中秋节
              }
            }
            if (y_m_d[1] == 10) {
              if (y_m_d[2] == 10) {
                return [e.date, true, "workday"];
              }
              if (y_m_d[2] >= 1 && y_m_d[2] <= 7) {
                return [e.date, false, "bank holiday"]; //国庆节
              }
            }
          }
          let dayInWeek = day_of_week.get(new Date(e.date), "Asia/Shanghai");
          let isBusinessDay = dayInWeek % 6 > 0;
          if (isBusinessDay) {
            return [e.date, isBusinessDay, "workday"];
          } else {
            return [e.date, isBusinessDay, "weekend"];
          }
        }),
        xAxisIndex: 3,
        yAxisIndex: 3,
        renderItem: function renderIsBusinessDay(params, api) {
          let [value0, value1, value2] = [
            api.value(0),
            api.value(1),
            api.value(2)
          ];
          // debugger
          let sized = api.size([value0, value1]);
          let coorded = api.coord([value0, value1]);
          return {
            type: "group",
            children: [
              {
                type: "rect",
                shape: {
                  height: params.coordSys.height,
                  x: coorded[0] - sized[0] / 2 + sized[0] * 0.1,
                  y: params.coordSys.y,
                  width: sized[0] * 0.8
                  // points:[[coorded[0],params.coordSys.y],[coorded[0]+2,params.coordSys.y+1]]
                },
                style: {
                  fill: value1 ? "transparent" : "#ff008000",
                  stroke: vue.gray_colors[2],
                  lineWidth: 1
                }
              },
              {
                /**@description 在rect里画一条从左上到右下的线 */
                type: "line",
                shape: {
                  x1: coorded[0],
                  y1: params.coordSys.y,
                  x2: coorded[0],
                  y2: params.coordSys.y + params.coordSys.height
                },
                style: {
                  stroke: value1 ? vue.gray_colors[2] : "transparent",
                  fill: "transparent"
                }
              },
              {
                /**@description 在rect里画一条从右上到左下的线 */
                type: "line",
                shape: {
                  x1: coorded[0] - sized[0] / 2 + sized[0] * 0.9,
                  y1: params.coordSys.y + params.coordSys.height / 2,
                  x2: coorded[0] - sized[0] / 2 + sized[0] * 0.1,
                  y2: params.coordSys.y + params.coordSys.height / 2
                },
                style: {
                  stroke: value1 ? vue.gray_colors[2] : "transparent",
                  fill: "transparent"
                }
              }
            ]
          };
        },
        tooltip: {
          formatter: function(params) {
            if (params && params.data && params.data.length) {
              let d = params.data;
              let workday = d[1];
              return `date : ${d[0]}<br>${d[2]}`;
            }
          }
        }
      };
    },
    center_rect_series_normal_start_types_count() {
      let vue = this;
      return {
        name: "rect-3",
        type: "custom",
        yAxisIndex: 4,
        xAxisIndex: 4,
        itemStyle: {
          color: this.gray_colors[2]
        },
        tooltip: {
          show: false
        },
        z: 2,
        data: this.raw_datas.map(e => {
          let normals = _.filter(
            _.map(_.mapValues(e.counts, (count, type) => [count, type])),
            ([count, type]) =>
              count > 0 && vue.abnormal_type2comment[type].startsWith("C")
          );
          let normal_type_counts = normals.length;
          return {
            value: [e.date, normal_type_counts]
          };
        }),
        tooltip: {
          formatter: function(params) {
            let dataIndex = params.dataIndex;
            let normals = _.filter(
              _.map(
                _.mapValues(
                  vue.raw_datas[dataIndex]["counts"],
                  (count, type) => [count, type]
                )
              ),
              ([count, type]) =>
                count > 0 && vue.abnormal_type2comment[type].startsWith("C")
            );
            let type_counts_str = normals
              .map(
                ([count, type]) =>
                  `${vue.abnormal_type2comment[type]} : ${count}`
              )
              .join("<br>");
            return `date : ${
              vue.raw_datas[dataIndex]["date"]
            } <br> ${type_counts_str}`;
          }
        },
        renderItem: function(params, api) {
          let [value0, value1, value2] = [
            api.value(0),
            api.value(1),
            api.value(2)
          ];
          let sized = api.size([value0, value1]);
          let coorded = api.coord([value0, value1]);
          return {
            type: "group",
            children: [
              {
                type: "rect",
                shape: {
                  height: params.coordSys.height,
                  x: coorded[0] - sized[0] / 2 + sized[0] * 0.1,
                  y: params.coordSys.y,
                  width: sized[0] * 0.8
                },
                style: {
                  fill: "transparent",
                  stroke: vue.gray_colors[2],
                  lineWidth: 1
                }
              },
              {
                type: "rect",
                shape: {
                  height: params.coordSys.height * (value1 / 2),
                  x: coorded[0] - sized[0] / 2 + sized[0] * 0.1,
                  y:
                    params.coordSys.y +
                    params.coordSys.height * (1 - value1 / 2),
                  width: sized[0] * 0.8
                },
                style: {
                  fill: vue.gray_colors[2],
                  // stroke: vue.gray_colors[2],
                  lineWidth: 0
                }
              }
            ]
          };
        }
      };
    },
    center_rect_series_normal_start_types_count_border() {
      let vue = this;
      return {
        name: "rect-3",
        type: "bar",
        yAxisIndex: 4,
        xAxisIndex: 4,
        itemStyle: {
          color: "transparent",
          borderColor: this.gray_colors[2],
          borderWidth: 1
        },
        tooltip: {
          show: true,
          formatter: function(params) {}
        },
        barGap: "-100%",
        data: this.raw_datas.map((e, i) => {
          let normals = _.filter(
            _.map(_.mapValues(e.counts, (count, type) => [count, type])),
            ([count, type]) =>
              count > 0 && vue.abnormal_type2comment[type].startsWith("C")
          );
          return {
            value: [e.date, 2],
            tooltip: {
              formatter: function() {
                let type_counts_str = normals
                  .map(
                    ([count, type]) =>
                      `${vue.abnormal_type2comment[type]} : ${count}`
                  )
                  .join("<br>");
                return `date : ${e.date} <br> ${type_counts_str}`;
              }
            }
          };
        })
      };
    },
    center_rect_series_abnormal_start_types_count() {
      let vue = this;
      let max_abnromal_counts = _.size(this.type_counts) - 2;
      return {
        name: "rect-4",
        type: "custom",
        yAxisIndex: 5,
        xAxisIndex: 5,
        itemStyle: {
          color: this.gray_colors[2]
        },
        z: 2,
        tooltip: {
          show: false
        },
        data: this.raw_datas.map(e => {
          let abnormals = _.filter(
            _.map(_.mapValues(e.counts, (count, type) => [count, type])),
            ([count, type]) =>
              count > 0 && !vue.abnormal_type2comment[type].startsWith("C")
          );
          let abnormals_length = abnormals.length;
          return {
            value: [e.date, abnormals_length / max_abnromal_counts]
          };
        }),
        renderItem: function(params, api) {
          let [value0, value1] = [api.value(0), api.value(1)];
          let sized = api.size([value0, value1]);
          let coorded = api.coord([value0, value1]);
          return {
            type: "group",
            children: [
              {
                type: "rect",
                shape: {
                  height: params.coordSys.height,
                  x: coorded[0] - sized[0] / 2 + sized[0] * 0.1,
                  y: params.coordSys.y,
                  width: sized[0] * 0.8
                },
                style: {
                  fill: "transparent",
                  stroke: vue.gray_colors[2],
                  lineWidth: 1
                }
              },
              {
                type: "rect",
                shape: {
                  height: params.coordSys.height,
                  x: coorded[0] - sized[0] / 2 + sized[0] * 0.1,
                  y: params.coordSys.y,
                  width: sized[0] * 0.8 * value1
                },
                style: {
                  fill: vue.gray_colors[2],
                  lineWidth: 0
                }
              }
            ]
          };
        },
        tooltip: {
          formatter: function(params) {
            let dataIndex = params.dataIndex;
            let e = vue.raw_datas[dataIndex];
            let abnormals = _.filter(
              _.map(_.mapValues(e.counts, (count, type) => [count, type])),
              ([count, type]) =>
                count > 0 && !vue.abnormal_type2comment[type].startsWith("C")
            );
            let type_counts_str = abnormals
              .map(
                ([count, type]) =>
                  `${vue.abnormal_type2comment[type]} : ${count}`
              )
              .join("<br>");
            return `date : ${e.date} <br> ${type_counts_str}`;
          }
        }
      };
    },
    center_rect_series_abnormal_start_types_count_border() {
      let vue = this;
      let max_abnromal_counts = _.size(this.type_counts) - 2;
      return {
        name: "rect-4",
        type: "bar",
        yAxisIndex: 5,
        xAxisIndex: 5,
        itemStyle: {
          color: "transparent",
          borderColor: this.gray_colors[2],
          borderWidth: 1
        },
        tooltip: {
          // show: false
        },
        z: 3,
        barGap: "-100%",
        data: this.raw_datas.map(e => {
          let abnormals = _.filter(
            _.map(_.mapValues(e.counts, (count, type) => [count, type])),
            ([count, type]) =>
              count > 0 && !vue.abnormal_type2comment[type].startsWith("C")
          );
          return {
            value: [e.date, max_abnromal_counts],
            tooltip: {
              formatter: function() {
                let type_counts_str = abnormals
                  .map(
                    ([count, type]) =>
                      `${vue.abnormal_type2comment[type]} : ${count}`
                  )
                  .join("<br>");
                return `date : ${e.date} <br> ${type_counts_str}`;
              }
            }
          };
        })
      };
    }
  },
  watch: {
    starterId: function(val, oldVal) {
      this.loadFromSource(val);
      this.$store.commit("brushedDatesAndTypes", {
        dates: [],
        types: []
      });
    },
    selectedDatas: function(val, oldVal) {
      // debugger;
      this.$emit("barSelect", this.selected);
      this.$store.commit("hasSelect", true);
      this.$store.commit("brushedDatesAndTypes", this.selected);
      // this.$_cache_testids_by_dates_and_types(
      //   this.selected["dates"],
      //   this.selected["types"]
      // );
    }
  },
  mounted: async function() {
    let chart = echarts.init(this.$refs["ele"], "macarons");
    this.chart = chart;
    let vue = this;

    chart.on("brushSelected", args => {
      // debugger
      let batch = args["batch"][0];

      /***@description 限制brushxAxisIndex情况下的事件响应
      if(batch.areas.length>0){
        let selected_series = batch.selected.filter(e=>e.dataIndex.length>0);
        if(selected_series.length){
          let dates = selected_series[0]['dataIndex'].map(e=>vue.dates[e]);
          let types = selected_series.map(e=>e['seriesName'].replace("type:",""));
          vue.selected['types']=types;
          vue.selected['dates']=dates;
        }
      }     
       */

      let types = batch["selected"]
        .filter(e => {
          return e["seriesName"].startsWith("type:");
        })
        .map(e => e["seriesName"].replace("type:", ""));
      let dates = batch["selected"][0]["dataIndex"].map(e => this.dates[e]);

      if (batch["areas"].length !== 0) {
        this.selected["types"] = types;
        this.selected["dates"] = dates;
      }
    });
    chart.on("click", params => {
      if (params.componentSubType === "bar") {
        this.selected["dates"] = [params.name];
        this.selected["types"] = [params.seriesName.replace("type:", "")];
      }
    });
    this.loadFromSource(this.starterId);
  },
  methods: {
    loadFromSource: async function(source_id) {
      this.chart.showLoading();
      //   let axresp = await axios.get("/static/foobrushv2.json");
      let axresp = await this.$http.get("starter/overview", {
        params: {
          starterId: source_id
        }
      });
      this.dataAdapter(axresp.data);
      this.chart.hideLoading();
      this.chart.clear(); //prevent types fresh error
      this.chart.setOption(this.chart_option());
    },
    dataAdapter(data) {
      // this.type_counts = data["global"]["type_counts"];
      this.$store.commit("type2counts", data["global"]["type_counts"]);
      let type_keys = Object.keys(this.type_counts);
      this.dates = data["global"]["data"].map(d => d.date);
      this.raw_datas = data["global"]["data"].map(d => {
        let counts = {};
        let total = 0;
        for (let key of type_keys) {
          counts[key] = d[key];
          total += counts[key];
        }
        return {
          date: d.date,
          counts: counts,
          total: total
        };
      });
    },
    brush(data) {
      console.log(data);
    },
    chart_option() {
      let _this = this;
      let option = {
        title: {},
        tooltip: {},
        toolbox: {
          top: 10,
          right: 0,
          itemSize: 15,
          orient: "vertical",
          showTitle: false,
          iconStyle: {
            color: this.gray_colors[1],
            borderColor: this.gray_colors[2]
          }
        },
        grid: [
          {
            show: false,
            height: "33%",
            top: "5%"
            // borderColor:"black"
          },
          {
            show: false,
            height: "28%",
            bottom: "14%"
            // borderColor:"black"
          },
          {
            /**@description 当日是否有测试 */
            height: "2.875%",
            top: `${40}%`
          },
          {
            /**@description 当日是否为工作日 ---- 不要了!!! */
            height: "2.875%",
            top: `${44.375}%`
          },
          {
            /**@description 当日正常启动类型的数量 */
            height: "2.875%",
            top: `${48.75}%`
          },
          {
            /**@description 当日异常启动类型的数量 */
            height: "2.875%",
            top: `${53.125}%`
          }
        ].map(e => {
          e["left"] = 210;
          e["right"] = 35;
          return e;
        }),
        xAxis: [
          {
            /**@description 上方坐标系的轴 */
            data: this.dates,
            // show: false,
            gridIndex: 0,
            splitLine: {
              show: false
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: this.gray_colors[0]
              }
            },
            axisLabel: {
              show: false
            },
            axisTick: {
              show: false
            }
          },
          {
            /**@description 下方坐标系的轴 */
            data: this.dates,
            gridIndex: 1,
            // name:"date",
            axisTick: {
              show: true,
              alignWithLabel: true,
              lineStyle: {
                color: this.gray_colors[0]
              },
              interval: function(index, value) {
                return index % 7 == 0 || index == _this.dates.length - 1;
              }
            },
            splitLine: {
              show: false
            },
            axisLine: {
              show: true,
              onZero: false,
              lineStyle: {
                color: this.gray_colors[0]
              }
            },
            axisLabel: {
              interval: function(index, value) {
                return index % 7 == 0 || index == _this.dates.length - 1;
              },
              formatter: function(value, index) {
                let y_m_d = value.split("-");
                let simple_month = ntdmn.toMonth(y_m_d[1]).substr(0, 3) + ".";
                if (index == 0) {
                  return `            ${simple_month}${y_m_d[2]},${y_m_d[0]}`;
                } else {
                  return `${simple_month}${y_m_d[2]}`;
                }
              },
              color: this.gray_colors[1],
              fontSize: this.font_size
            },
            boundaryGap: true,
            position: "bottom",
            offset: 10
            // show: false,
          },
          ...[
            {
              /**@description 当日是否有测试 */
              data: this.dates,
              gridIndex: 2,
              show: true
              // name: "test day"
            },
            {
              /**@description 当日是否为工作日 */
              data: this.dates,
              gridIndex: 3
              // name: "work day"
              // show: false,
              // name:"workday"
            },
            {
              /**@description 当日正常启动类型的数量 */
              data: this.dates,
              gridIndex: 4
              // name: "normal types"
              // show: false
            },
            {
              /**@description 当日异常启动类型的数量 */
              data: this.dates,
              gridIndex: 5
              // name: "anomaly types"
              // show: false
            }
          ].map(e => {
            e = {
              ...e,
              nameLocation: "start",
              axisLine: {
                show: false,
                onZero: false
              },
              axisLabel: {
                show: false
              },
              axisTick: {
                show: false
              },
              nameTextStyle: {
                color: _this.gray_colors[1]
              },
              offset: -8
            };
            return e;
          }),
          {
            /**@description 下方坐标系的x轴的0位置占位 */
            data: this.dates,
            gridIndex: 1,
            position: "top",
            axisLine: {
              lineStyle: {
                color: this.gray_colors[0]
              }
            },
            axisLabel: {
              show: false
            },
            axisTick: {
              show: false
            }
          }
        ],
        yAxis: [
          {
            type: "value",
            gridIndex: 0,
            // z: 4,
            splitLine: {
              show: true,
              lineStyle: {
                color: this.gray_colors[0],
                type: "dotted",
                opacity: 0.5
              }
            },
            splitArea: {
              show: false
            },
            splitNumber: 4,
            name: "Test Count",
            nameGap: 52,
            nameLocation: "center",
            nameTextStyle: {
              color: this.gray_colors[1],
              // fontFamily: "Arial",
              fontSize: this.font_size,
              textShadowColor: "transparent",
              textShadowBlur: 0,
              textShadowOffsetX: -55,
              textShadowOffsetY: 85
            },
            nameRotate: 90,
            axisLine: {
              lineStyle: {
                color: this.gray_colors[0]
              }
            },
            axisLabel: {
              color: this.gray_colors[1],
              fontSize: this.font_size
            }
          },
          {
            inverse: true,
            gridIndex: 1,
            splitLine: {
              show: true,
              lineStyle: {
                color: this.gray_colors[0],
                type: "dotted",
                opacity: 0.5
              }
            },
            splitArea: {
              show: false
            },
            splitNumber: 4,
            name:"Test Count", //"Anomaly Count",
            nameGap: 52,
            nameRotate: 90,
            nameLocation: "center",
            nameTextStyle: {
              color: this.gray_colors[1],
              // fontFamily: "Arial",
              fontSize: this.font_size,
              textShadowColor: "transparent",
              textShadowBlur: 0,
              textShadowOffsetX: -55,
              textShadowOffsetY: -90
            },
            axisLine: {
              lineStyle: {
                color: this.gray_colors[0]
              }
            },
            axisLabel: {
              color: this.gray_colors[1],
              fontSize: this.font_size
            }
          },
          {
            /**@description 当日是否有测试 */
            gridIndex: 2,
            show: false
          },
          {
            /**@description 当日是否为工作日 */
            gridIndex: 3,
            show: false
          },
          {
            /**@description 当日正常启动类型的数量 */
            gridIndex: 4,
            show: false,
            max: 2,
            min: 0
          },
          {
            /**@description 当日异常启动类型的数量 */
            gridIndex: 5,
            show: false,
            min: 0,
            max: _.size(this.type_counts) - 2
          }
        ],
        dataZoom: [],
        brush: {
          toolbox: ["lineX", "clear"],
          throttleType: "debounce",
          throttleDelay: 1000,
          removeOnClick: false,
          // yAxisIndex: [0, 1],
          // xAxisIndex:[0,1],
          outOfBrush: {
            colorAlpha: 1
          },
          inBrush: {
            // colorLightness: 0.9
            // colorSaturation: 0.1
          },
          brushStyle: {
            color: "#ff8c1911",
            borderColor: "orange",
            borderWidth: 1
          }
          // z: 1
        },
        legend: [
          {
            data: this.bar_serieses
              .filter(e => e["stack"] == "normal")
              .map(e => e["name"]),
            top: 111 + this.debug_plus
          },
          {
            data: [
              {
                name: "rect-1",
                icon: "image:///static/rect-icon/1.svg"
              },
              {
                name: "rect-2",
                icon: "image:///static/rect-icon/2.svg"
              },
              {
                name: "rect-3",
                icon: "image:///static/rect-icon/3.svg"
              },
              {
                name: "rect-4",
                icon: "image:///static/rect-icon/4.svg"
              }
            ],
            top: 23,
            // itemHeight:this.font_size-2,
            itemWidth: 18
          },
          {
            data: (() => {
              let Ax = this.bar_serieses
                .filter(e => {
                  return (
                    e["stack"] != "normal" && e["name"].indexOf("-1") == -1
                  );
                })
                .map(e => e.name)
                .sort((name_1, name_2) => {
                  let type_1 = name_1.replace("type:", "");
                  let type_2 = name_2.replace("type:", "");
                  return _this.type_counts[type_2] - _this.type_counts[type_1];
                });
              return [...Ax, "type:-1"];
            })(),
            top: 182
          }
        ].map(e => {
          e["formatter"] = function(name) {
            //name的值形如`type:-1`
            let type_id = name.replace("type:", "");
            let type_id_number = parseInt(type_id);
            if (!Number.isNaN(type_id_number)) {
              let count = _this.type_counts[type_id];
              let comment = _this.abnormal_type2comment[type_id];
              if(comment.startsWith("C")){
                comment = comment.replace("C","T");
              }
              count = formatter(count);
              return `${comment} : ${count}`;
            } else {
              let rect_number = Number(name.replace("rect-", ""));
              if (rect_number == 1) {
                return "test day";
              }
              if (rect_number == 2) {
                return "work day";
              }
              if (rect_number == 3) {
                // return "normal types";
                return "typical start modes"
                // return "large-quantity types"
              }
              if (rect_number == 4) {
                // return "anomaly types";
                return "atypical start modes"
                // return "small-quantity types"
              }
              return name;
            }
          };
          e["tooltip"] = {
            show: true,
            formatter: function(params, ticket, callback) {
              let type_id = parseInt(params["name"].replace("type:", ""));
              if (Number.isNaN(type_id)) {
                return null;
              }
              let debug_color = _this.abnormal_type2color[type_id];
              return `total:${_this.type_counts[type_id]}
              `; // (debug:${type_id}:${debug_color})
            }
          };
          // e["type"] = "scroll";
          e["orient"] = "vertical";
          e["left"] = 10;
          e["padding"] = 5;
          e["itemGap"] = 2;
          e["itemWidth"] = e["itemWidth"] || 20;
          e["itemHeight"] = e["itemHeight"] || this.font_size;
          e["textStyle"] = {
            // padding:0,
            // width:15,
            fontSize: this.font_size,
            color: this.gray_colors[1]
          };
          return e;
        }),
        series: [
          ...this.bar_serieses,
          this.center_rect_series_is_business_day,
          this.center_rect_series_has_tests,
          this.center_rect_series_normal_start_types_count,
          // this.center_rect_series_normal_start_types_count_border,
          this.center_rect_series_abnormal_start_types_count
          // this.center_rect_series_abnormal_start_types_count_border
        ],
        graphic: this.opt_graphic
      };
      return option;
    },
    /**@deprecated 没有用的东西 */
    $_cache_testids_by_dates_and_types: async function(dates, types) {
      // let cached = (await axios.get(
      //   "/starter/overview/selection/cache_testids/",
      //   {
      //     params: {
      //       starterId: this.starterId,
      //       dates: dates,
      //       types: types
      //     }
      //   }
      // )).data;
      // dbg("%j", cached);
    }
  }
};
</script>

<style lang="scss">
.global-graph {
  width: 1880px;
  height: 279px;
}
</style>
